wx.cloud.init({
  env: 'database-2p2zg'
})
const db = wx.cloud.database()
// orderBy方法规定排序
Page({
  data: {
    faculty: ['文传', '电气', '外国语', '艺创', '医管', '商学院', '护理系', '会计', '公管', '音乐系','继教'],
    demands: [],
  },
  pageNumber: { skip: 0 },
  getData: function (req,callback) {
    this.data.openid = wx.getStorageSync('openID')
    wx.showLoading({
      title: '正努力加载数据',
    })
    // res =>{}声明一个函数，传入res作为参数
    req.skip(this.pageNumber.skip).get().then(res => {
      let oldData = this.data.demands
      this.setData({ demands: oldData.concat(res.data), openid: this.data.openid})
      this.pageNumber.skip += 20
      res => {
        callback,
          this.pn.skip += 20
      }
      wx.hideLoading()
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      if(options.type){
        this.data.info = db.collection('school-request').where({
          type: '知识',
          faculty:options.type
        }).orderBy('creatTime', 'desc')
      }
      else{
        this.data.info = db.collection('school-request').where({
          type: '知识',
        }).orderBy('creatTime', 'desc')
      }
    this.setData({ type: options.type })
    this.getData(this.data.info)
  },

  classify:function(e){
    var index = e.currentTarget.dataset.index
    this.setData({order:index,picked:true,fade:false})
    // 使用重定向可立即返回首页，避免产生多层页面（navigateTo等会产生多级页面）relauch则关闭了所有页面无法返回首页
    wx.redirectTo({
      url: '/pages/knowledge/knowledge?type=' + this.data.faculty[index],
    })
  },

  onPullDownRefresh: function () {
    wx.showLoading({
      title: '正努力加载数据',
    })
    this.data.info.get().then(res => {
      this.setData({ demands: res.data })
      wx.hideLoading()
    })
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   * 新建文件，搬代码解决无法触发的问题
   */
  onReachBottom: function () {
    this.getData(this.data.info)
  },

  toMessage: function () {
    var openid = this.data.openid
    wx.navigateTo({
      url: '/pages/message/message' + openid,
    })
  },

  toHead: function () {
    wx.pageScrollTo({
      scrollTop: 0,
    })
  },

  onShareAppMessage: function () {
    return {
      title: '南苑圈子，方便你我',
      path: 'pages/knowledge/knowledge',
    }
  }
})